﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;

namespace cludg.Repository.Images.HttpServerFile
{
	public class ImageRepository : IImageRepository
	{
		protected readonly string ImagesFolder;

		protected readonly HttpServerUtility Server;

		public ImageRepository(HttpServerUtility server, string imagesFolder)
			: base()
		{
			Server = server;
			ImagesFolder = imagesFolder;
		}

		protected string VirtualFolder { get { return ImagesFolder; } }
		protected string GetImageFolder(string id)
		{
			if (String.IsNullOrEmpty(id) || (id.Length < 2))
				return "";

			return id.Substring(0, 2);
		}
		protected string RealFolder { get { return Server.MapPath(Path.Combine("~", VirtualFolder)); } }

		public string Add(string format, Stream stream)
		{
			string id = Path.ChangeExtension(Guid.NewGuid().ToString().Replace("-", ""), format);
			string folder = Path.Combine(RealFolder, GetImageFolder(id));
			if (!Directory.Exists(folder))
				Directory.CreateDirectory(folder);
			string path = Path.Combine(folder, id);

			using (var file = File.Create(path))
			{
				stream.CopyTo(file);
				file.Flush();
				file.Close();
			}

			return id;
		}

		public string GetUrl(string imageId)
		{
			string imageUrl = string.Empty;
			if (!string.IsNullOrEmpty(imageId))
			{
				imageUrl = "/" + Path.Combine(VirtualFolder, GetImageFolder(imageId), imageId).Replace(Path.DirectorySeparatorChar, '/');
			}
			return imageUrl;
		}

		public Stream GetStream(string imageId)
		{
			string path = Path.Combine(RealFolder, GetImageFolder(imageId), imageId);
			if (!File.Exists(path))
				return null;

			return File.OpenRead(path);
		}

		public void Delete(string imageId)
		{
			string path = Path.Combine(RealFolder, GetImageFolder(imageId), imageId);
			if (File.Exists(path))
				File.Delete(path);
		}
	}
}
